package com.dys.dao.impl;

import com.dys.dao.DepartmentDao;
import com.dys.entity.Department;
import com.dys.util.ConnectionPool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 疾风
 * @ClassName: DepartmentDaoImpl
 * @Description: 部门查询
 * @CreateDate: 2024/10/11
 * @Version: v1.0.0
 */
public class DepartmentDaoImpl implements DepartmentDao {
    @Override
    public List<Department> selectDropDownToSelectAllDepartment() {
        // 1.获取数据库连接
        Connection conn = ConnectionPool.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Department> list = new ArrayList<>();
        try {
            // 预编译SQL
            ps = conn.prepareStatement("select * from t_department");
            // 执行SQL
            rs = ps.executeQuery();
            // 将数据封装为Department对象，添加入List集合中：
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                Department department = new Department(id, name);
                list.add(department);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭连接资源
            ConnectionPool.close(conn, ps, rs);
        }
        return list;
    }
}
